package com.onluy.frameworkcloud.tools.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class JsonUtil
{
  protected static Logger log = LoggerFactory.getLogger(JsonUtil.class);
  private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

  public static String toJson(List<?> result)
  {
    return toJson(result, null);
  }

  public static String toJsonByEasyPagination(List<?> result)
  {
    return toJson(result, "pager");
  }

  private static String toJson(List<?> result, String actionType)
  {
    if ((result != null) && (result.size() > 0) && ((result.get(0) instanceof Map))) {
      for (int i = 0; i < result.size(); i++) {
        Map data = (Map)result.get(i);

        if (data.get("STATE") != null) {
          data.put("state", data.get("STATE"));
          data.remove("STATE");
        }
        if (data.get("PARENTID") != null) {
          data.put("parentId", data.get("PARENTID"));
          data.remove("PARENTID");
        }
        if (data.get("ID") != null) {
          data.put("id", data.get("ID"));
          data.remove("ID");
        }
        if (data.get("TEXT") != null) {
          data.put("text", data.get("TEXT"));
          data.remove("TEXT");
        }
      }

    }

    String datas = data2JsonString(result);
    return datas;
  }

  public static String data2JsonString(Object src)
  {
    if (src != null) {
      SerializeConfig mapping = new SerializeConfig();

      mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
      mapping.put(Timestamp.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));

      return JSONArray.toJSONString(src, mapping, new SerializerFeature[0]);
    }
    return "";
  }
}